// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  // 给定 DYNAMIC_CURRENT_ENV 常量：接下来的 API 调用都将请求到与该云函数当前所在环境相同的环境
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  let DB = cloud.database().collection('login_orderList');
  if (event.type == 'getopenid') {
    //获取用户openid
    return { event, openid: wxContext.OPENID };

  } else if (event.type == 'getpay') {
    //获取已支付订单和已完成订单  骑手的识别id
    let getpay = await DB.where({ rider_id: event.rider_id, ifover_order: false }).get();
    let getoutpay = await DB.where({ rider_id: event.rider_id, ifover_order: true }).get();
    return { getpay, getoutpay };

  } else if (event.type == 'update_order') {
    //更新物流状态
    let _ = cloud.database().command;
    let update_data = await DB.doc(event.id).update({
      data: {
        order_code: event.order_code,
        order_state: _.push(event.order_title)
      }
    });
    let order_datas = await DB.doc(event.id).get();
    return { update_data, order_datas };

  } else if (event.type == 'success_update_order') {
    let _ = cloud.database().command;
    const DB2 = cloud.database().collection('rider_inf');
    let update_data = await DB.doc(event.id).update({
      data: {
        order_code: event.order_code,
        order_state: _.push(event.order_title),
        ifover_order: true
      }
    });
    //更新骑手的余额
    let money = Math.round(event.pay_money * 100) / 100
    let update_rider = await DB2.doc(event.rider_inf_id).update({
      data: {
        rider_money: _.inc(money),
        rider_moneylist: _.push(event.order_inf)
      }
    })
    let order_datas = await DB.doc(event.id).get();
    return { update_data, update_rider, order_datas };

  } else if (event.type == 'daisho_update_order') {
    //代收快递员接单 1.上传到数据库中。
    var _ = cloud.database().command;
    let daisho_update = await DB.add({ data: event.datas });
    // 2.删除支付订单
    let delect_order = await cloud.database().collection('wait_right').doc(event.delect_id).remove();
    // 更新骑手信息
    const DB2 = cloud.database().collection('rider_inf');
    let rider_inf = await DB2.doc(event.datas.pay_courier_inf._id).update({
      data: { ride_number: _.inc(1) }
    })
    return { daisho_update, delect_order, rider_inf };

  }else if (event.type == 'select_order') {
    //通过订单号查询订单
    return  await DB.where({order_number:event.order_code}).get();
  }



}